//
//  SearchViewController.m
//  LogisticsFollow
//
//  Created by JustFei on 2016/12/21.
//  Copyright © 2016年 manridy. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTableViewCell.h"
#import "OrderModel.h"
#import "ResultViewController.h"

@interface SearchViewController () < UITableViewDelegate ,UITableViewDataSource >

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *resetButton;
@property (weak, nonatomic) IBOutlet UIButton *searchButton;
@property (nonatomic ,strong) NSArray *funcArr;
@property (nonatomic ,strong) NSArray *placeHoldArr;
@property (nonatomic ,strong) UIDatePicker *datePickerView;
@property (nonatomic ,strong) UITextField *currentTextField;
@property (nonatomic ,strong) UITextField *nameTextField;
@property (nonatomic ,strong) UITextField *orderTextField;
@property (nonatomic ,strong) UITextField *startTextField;
@property (nonatomic ,strong) UITextField *endTextField;
@property (nonatomic ,copy) NSString *dateStr;
@property (nonatomic ,strong) MBProgressHUD *hud;

@end



@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.scrollEnabled = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchTableViewCell" bundle:nil] forCellReuseIdentifier:@"searchCell"];
    
    self.navigationItem.title = @"高级搜索";
    self.navigationController.navigationBar.tintColor = kWhiteColor;
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = backItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.funcArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    
    cell.functionLabel.text = self.funcArr[indexPath.row];
    cell.textField.placeholder = self.placeHoldArr[indexPath.row];
    
    switch (indexPath.row) {
        case 0:
        {
            self.orderTextField = cell.textField;
        }
            break;
        case 1:
        {
            self.nameTextField = cell.textField;
        }
            break;
        case 2:
        {
            cell.textField.enabled = NO;
            self.startTextField = cell.textField;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
            break;
        case 3:
        {
            cell.textField.enabled = NO;
            self.endTextField = cell.textField;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
            
        default:
            break;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (![self.orderTextField isExclusiveTouch]) {
        [self.orderTextField resignFirstResponder];
    }
    
    if (![self.nameTextField isExclusiveTouch]) {
        [self.nameTextField resignFirstResponder];
    }
    if (indexPath.row == 2 || indexPath.row == 3) {
        self.currentTextField = ((SearchTableViewCell *)[tableView cellForRowAtIndexPath:indexPath]).textField;
        [self showInfoPickerView];
    }
}


#pragma mark - Action
- (IBAction)resetAction:(UIButton *)sender
{
    self.orderTextField.text = @"";
    self.nameTextField.text = @"";
    self.startTextField.text = @"";
    self.endTextField.text = @"";
}

- (IBAction)searchAction:(UIButton *)sender
{
    if (self.orderTextField.text && self.nameTextField.text && self.startTextField.text && self.endTextField.text) {
        // 启动系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        //启动我的风火轮
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.mode = MBProgressHUDModeIndeterminate;
        self.hud.label.text = @"Loading";
        
        //服务器给的域名
        NSString *domainStr = kSearchOrderPort;
        
        //假如需要提交给服务器的参数是key＝1,class_id=100
        //创建一个可变字典
        NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
        NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
        //往字典里面添加需要提交的参数
        [parametersDic setObject:guid forKey:@"guid"];
        [parametersDic setObject:self.orderTextField.text forKey:@"orderCode"];
        [parametersDic setObject:self.nameTextField.text forKey:@"customerName"];
        [parametersDic setObject:[self dateFormateWith:self.startTextField.text] forKey:@"startDate"];
        [parametersDic setObject:[self dateFormateWith:self.endTextField.text]  forKey:@"endDate"];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [manager POST:domainStr parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                // 隐藏系统风火轮
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                
                //json解析
                NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                //转成jsonModel
                OrderModel *model = [[OrderModel alloc] initWithDictionary:resultDic error:nil ];
                
                if (model.isSuccess) {
                    [self.hud hideAnimated:YES afterDelay:1];
                    //TODO:search 订单调试完成，准备做订单展示，ps：订单号支持大小写
                    ResultViewController *vc = [[ResultViewController alloc] init];
                    vc.dataArr = model.result;
                    if (model.result.count != 0) {
                        [self.navigationController pushViewController:vc animated:YES];
                    }else {
                        self.hud.label.text = @"没有订单";
                        [self.hud hideAnimated:YES afterDelay:1];
                    }
                }else {
                    [self doFailPOST];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                [self doFailPOST];
            }];
        });
    }
}

- (void)doFailPOST
{
    self.hud.label.text = @"请求失败，请检查网络";
    [self.hud hideAnimated:YES afterDelay:1.5];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (![self.orderTextField isExclusiveTouch]) {
        [self.orderTextField resignFirstResponder];
    }
    
    if (![self.nameTextField isExclusiveTouch]) {
        [self.nameTextField resignFirstResponder];
    }
}

- (NSString *)dateFormateWith:(NSString *)dateStr
{
    [dateStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    return dateStr;
}

#pragma mark - 懒加载
- (NSArray *)funcArr
{
    if (!_funcArr) {
        _funcArr = @[@"订单编号",@"客户名称",@"开始日期",@"结束日期"];
    }
    
    return _funcArr;
}

- (NSArray *)placeHoldArr
{
    if (!_placeHoldArr) {
        _placeHoldArr = @[@"请输入订单号",@"请输入用户名",@"请输入",@"请输入"];
    }
    
    return _placeHoldArr;
}

- (void)showInfoPickerView
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //获取到该cell的label对象，修改text
        if (self.dateStr) {
            self.currentTextField.text = self.dateStr;
        }
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    
    self.datePickerView = [[UIDatePicker alloc] initWithFrame:XXF_CGRectMake(0, 0, alert.view.frame.size.width - 30, 216)];
    self.datePickerView.tag = 1000;
    self.datePickerView.datePickerMode = UIDatePickerModeDate;
    [self.datePickerView setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    // 设置时区
    [self.datePickerView setTimeZone:[NSTimeZone localTimeZone]];
    // 设置当前显示时间
    [self.datePickerView setDate:[NSDate date] animated:YES];
    // 设置UIDatePicker的显示模式
    [self.datePickerView setDatePickerMode:UIDatePickerModeDate];
    // 当值发生改变的时候调用的方法
    [self.datePickerView addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    [alert.view addSubview:self.datePickerView];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)datePickerValueChanged:(UIDatePicker *)datePicker
{
    DLog(@"%@",datePicker.date);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd"];
    self.dateStr = [formatter stringFromDate:datePicker.date];
}

@end
